const Controller = require('egg').Controller;
const Redis = require("ioredis")
const fs = require("fs")
const jwt = require("jsonwebtoken")

const sso = {
    "username": "Jay",
    "password": "123456",
    "app": {
        "6gJGBl2Fqy": {
            secret: "app_1", token: ""
        },
        "RQmErh8ef": {
            secret: "app_2", token: ""
        },
    }
}
class TrialController extends Controller {
    // 30秒内限制5次
    async limitVehicle() {
        const KEY = "lottery";
        // 30秒内操作5次限流
        const TIME = 30;
        const LIMIT = 5;
        const redis = new Redis();
        const data = fs.readFileSync("app/script/limit.lua")
        // redis中通过eval可执行lua脚本，redis.eval(lua脚本, 键的数量, key, [key...]键列表，arg, arg[arg...]参数列表，回调函数)
        const res = await redis.eval(data.toString(), 1, KEY, TIME, LIMIT)
        this.ctx.send({ data: res })
    }
    // 缓存
    async cache() {
        const { ctx } = this;
        ctx.send({ msg: "成功" })
    }
    // 生成token
    getToken(appId) {
        // 正常情况下使用redis存储token设置过期时间
        // 这里简单点存储的负载信息就是appId
        const token = jwt.sign({ appId }, sso.app[appId].secret)
        return token;
    }

    // 登录
    // 需要登录的页面，一进页面就调登录接口，如果登录过直接返回token，未登录或过期跳转登录页面
    async login() {
        const { ctx } = this;
        const { appId, redirect_url } = ctx.query;
        console.log(appId, redirect_url);
        let token;
        // sso登录中心有登录过
        if (sso.username) {
            // 如果该应用已经登录过了，直接返回token
            if (sso.app[appId].token) {
                token = sso.app[appId].token;
            } else {
                // 之后的应用没有token就生成个token返回
                const _token = this.getToken(appId)
                token = _token;
            }
            console.log(token);
            console.log(`${redirect_url}?token=${token}`);
            ctx.redirect(`${redirect_url}?token=${token}`)

        } else {
            // 否则前往登录页
            const html = fs.readFileSync("public/sso.html", "utf-8");
            ctx.body = html;
        }
    }
    async protected() {
        const { ctx } = this;
        const { username, password, appId, redirect_url } = ctx.request.body;
        const token = this.getToken(appId)
        sso.username = username;
        sso.password = password;
        sso.app[appId].token = token;
        ctx.redirect(`${redirect_url}?token=${token}`)
    }

}

module.exports = TrialController;

